//
//  TransferOutViewController.m
//  TenMinDemo
//
//  Created by Shawn Li on 2021/3/8.
//  Copyright © 2021 CYXiang. All rights reserved.
//

#import "TransferOutViewController.h"
#import "TransferOutConfirmViewController.h"
#import "OperateResultViewController.h"
#import "BaseTextField.h"
#import "CYXBaseRequest.h"
#import "TransferOutConfig.h"
#import "SafetyConfirmView.h"
#import "SimplePromptView.h"
#import "PicVerCodeView.h"
#import "TransferRecordViewController.h"
#import "CommonTool.h"

@interface TransferOutViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet BaseTextField *addrInput;
@property (weak, nonatomic) IBOutlet BaseTextField *amountInput;
@property (weak, nonatomic) IBOutlet BaseTextField *noteInput;
@property (weak, nonatomic) IBOutlet UILabel *coinSym;
@property (weak, nonatomic) IBOutlet UILabel *balanceInfo;
@property (weak, nonatomic) IBOutlet UISlider *feeSlider;
@property (nonatomic, strong) TransferOutConfig *configM;
@property (weak, nonatomic) IBOutlet UILabel *feeBottomInfo;
@property (weak, nonatomic) IBOutlet UILabel *feeRightInfo;
@property (weak, nonatomic) IBOutlet UILabel *feeLabel;
@property (weak, nonatomic) IBOutlet UILabel *feeMan;
@property (weak, nonatomic) IBOutlet UILabel *feeKuai;
@property (weak, nonatomic) IBOutlet UIButton *allBtn;
@property (weak, nonatomic) IBOutlet UIButton *doneBtn;
@property (weak, nonatomic) IBOutlet UILabel *notesLimitLabel;

@property (nonatomic,strong) SafetyConfirmView* safetyView;

/// <#注释#>
@property (nonatomic, assign) BOOL isAll;

@end

@implementation TransferOutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getTsfOutConfig_net];
    // Do any additional setup after loading the view from its nib.
}

- (void)setupUI{
    [super setupUI];
    self.title = [NSString stringWithFormat:@"%@ %@",LCLocalString(@"transfer_out"),self.coinM.name];
    
    [self setRightNavItem:LCLocalString(@"log_jl") font:[UIFont boldSystemFontOfSize:14] color:[UIColor colorWithHexString:@"#935bff"] icon:nil];
    
    [self.doneBtn setTitle:LCLocalString(@"confirm") forState:(UIControlStateNormal)];
    [self.allBtn setTitle:LCLocalString(@"all") forState:(UIControlStateNormal)];
    
    self.addrInput.placeholderColor = [UIColor colorWithHexString:@"#4d5273"];
    self.addrInput.placeholder = LCLocalString(@"tsf_out_qsrdz");
    self.amountInput.placeholderColor = [UIColor colorWithHexString:@"#4d5273"];
    self.amountInput.placeholder = LCLocalString(@"tsf_out_amount_plh");
    self.noteInput.placeholderColor = PlhColor;
    self.noteInput.placeholder = LCLocalString(@"notes_plh");
    
    self.coinSym.text = self.coinM.name;
    
}

- (void)rightNavItemClick:(id)sender{
    TransferRecordViewController *vc = LoadVCFormXib(TransferRecordViewController);
    vc.coinM = self.coinM;
    vc.listType = -1;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (BOOL)chenkInput{
    if (!self.addrInput.text.length) {
        LCInfoHUD(self.addrInput.placeholder, 1);
        return NO;
    }
    if (!self.amountInput.text.length) {
        LCInfoHUD(self.amountInput.placeholder, 1);
        return NO;
    }
    if ([self.amountInput.text doubleValue] > self.configM.balance) {
        LCInfoHUD(LCLocalString(@"kyyebz"), 1);
        return NO;
    }
    
    return YES;
}
- (IBAction)allAction:(id)sender {
    self.isAll = YES;
    self.amountInput.text = [NSString stringWithFormat:@"%@",@(self.configM.balance)];
}

- (IBAction)confirmAction:(id)sender {
    if (![self chenkInput]) {
        return;
    }
//    TransferOutConfirmViewController *vc = LoadVCFormXib(TransferOutConfirmViewController);
//    [self.navigationController pushViewController:vc animated:YES];
    
    LRWeakSelf(self);
    if (!self.safetyView) {
        self.safetyView = [[SafetyConfirmView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT)];
        self.safetyView.confirmType = @"1";
        self.safetyView.actionBlock = ^(NSInteger actionFlag,NSDictionary *info) {
            if (actionFlag == 0) {
                
            }else if (actionFlag == 1){
//                [weakself showPrompt:@"23423423423"];
                [weakself transferOut:info];
            }else if (actionFlag == 2){
                [weakself getPicVerCode_net];
            }
        };
    }
    self.safetyView.phoneNum = self.configM.phone;
    [self.safetyView showInView:self.navigationController.view];
}

- (void)transferOut:(NSDictionary *)safeInfo{
//    CGFloat amount = self.amountInput.text.doubleValue;
    BOOL isAll = self.isAll;
    CGFloat fee = self.feeSlider.value;
    if (!self.configM.requireFee) {
        fee = 0;
    }
    NSDictionary *param = @{
        @"assetId":@(self.coinM.id),
        @"amount":self.amountInput.text,
        @"toAddress":self.addrInput.text,
        @"remark":self.noteInput.text,
        @"fee":@(fee),
        @"payPassword":safeInfo[@"pswCode"],
        @"validateCode":safeInfo[@"verCode"],
        @"transferAll":@(isAll)
    };
    
    [CYXBaseRequest postWithUrl:API_transferOut param:param resultClass:nil success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            LCInfoHUD(@"转出成功", 1);
            [self showTransferOutDone];
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
    
}

- (void)showTransferOutDone{
    OperateResultViewController *vc = LoadVCFormXib(OperateResultViewController);
    vc.type = 1;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)getPicVerCode_net{
    PicVerCodeView *view = [[PicVerCodeView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT)];
    view.gvcApi = API_sendTsfPicVerCode;
    LRWeakSelf(self);
    view.actionBlock = ^(NSInteger index,NSString *gvCode) {
        CYXLog(@"%zd",index);
        if(index == 1){
            [self getPhoneVerCode_net:gvCode];
        }
    };
    
    [view showInView:self.navigationController.view];
}

- (void)getPhoneVerCode_net:(NSString *)gvCode{
    NSDictionary *param = @{@"gvc":gvCode};
    [CYXBaseRequest postWithUrl:API_sendTsfPhoneVerCode param:param resultClass:nil success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else if ([res isEqual: RequestSuccessCode]){
            LCInfoHUD(LCLocalString(@"yzmyfs"), 1);
            [self.safetyView verBeginRun];
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
}

- (void)showPrompt:(NSString *)msg{
    
    SimplePromptView *view = [[SimplePromptView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT)];
    LRWeakSelf(self);
    view.doneBlock = ^{
        [weakself showTransferOutDone];
    };

    [view showInView:self.navigationController.view];
    
//    [self.navigationController.view addSubview:view];
}



#pragma mark -

- (void)getTsfOutConfig_net{
    NSDictionary *param = @{@"assetId":@(self.coinM.id)};
    [CYXBaseRequest postWithUrl:API_getTransferLoad param:param resultClass:[TransferOutConfig class] success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            self.configM = res;
            [self refreshView];
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
}

- (void)refreshView{
    self.addrInput.text = @"";
    self.balanceInfo.text = [NSString stringWithFormat:@"可用 %@ %@",@(self.configM.balance),self.configM.feeAssetName];
    self.feeSlider.minimumValue = self.configM.minFee;
    self.feeSlider.maximumValue = self.configM.maxFee;
    
    self.feeLabel.hidden = !self.configM.requireFee;
    self.feeRightInfo.hidden = !self.configM.requireFee;
    self.feeSlider.hidden = !self.configM.requireFee;
    self.feeMan.hidden = !self.configM.requireFee;
    self.feeKuai.hidden = !self.configM.requireFee;
    self.feeBottomInfo.hidden = !self.configM.requireFee;
    
    [self configFee:self.configM.minFee];
   
}
- (IBAction)sliderChange:(UISlider *)sender {
    [self configFee:sender.value];
}

- (void)configFee:(CGFloat)fee{
    
    NSString *valueS = [NSString stringWithFormat:@"%.1lf",fee];
    CGFloat value = [[NSDecimalNumber decimalNumberWithString:valueS] doubleValue];
   
    self.feeBottomInfo.text = [NSString stringWithFormat:@"%.1lf sat/b",value];
    CGFloat info1 = [CommonTool floatFormat:value * self.configM.gasOrBytes];
    CGFloat info2 = [CommonTool floatFormat:info1 * self.configM.coinToUsdtRate];
    self.feeRightInfo.text = [NSString stringWithFormat:@"%@ %@ ≈ %.2lf usdt",@(info1),self.configM.feeAssetName,info2];
   
}

#pragma mark-

-(void)keyboardChangeFrame:(NSNotification*)noti{

    CGRect rect= [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    NSLog(@"%@", noti.userInfo);
    CGFloat keyboardheight = rect.size.height;
    CGFloat duration=[noti.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    CGFloat curve=[noti.userInfo[UIKeyboardAnimationCurveUserInfoKey]doubleValue];

    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        self.safetyView.bgBottom.constant = keyboardheight - 30;
        [self.safetyView layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

-(void)keyboardHide:(NSNotification *)noti
{
    [self.view endEditing:YES];

    [UIView animateWithDuration:0.35 animations:^{
        self.safetyView.bgBottom.constant = 0;
        [self.safetyView layoutIfNeeded];
      
    } completion:^(BOOL finished) {
        
    }];

}

#pragma mark-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.amountInput) {
        self.isAll = NO;
    }
    if (textField == self.noteInput){
        [self performSelector:@selector(configLimit) withObject:nil afterDelay:0.05];
    }
    return YES;
}

- (void)configLimit{{
    [self configInputLimit:self.noteInput limit:50 label:self.notesLimitLabel];
    
}}

- (void)configInputLimit:(UITextField *)input limit:(NSInteger)limit label:(UILabel *)label{
    if (limit <= 0) {
        return;;
    }
    NSString *curText = input.text;
    if (curText.length > limit) {
        curText = [curText substringToIndex:limit];
        input.text = curText;
    }
    label.text = [NSString stringWithFormat:@"%@/%@",@(input.text.length),@(limit)];
}


@end
